
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:path_provider/path_provider.dart';
import 'package:rxdart/rxdart.dart';
import 'package:wis_flutter/wis_component/notification/notificationModel.dart';


final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =FlutterLocalNotificationsPlugin();
final BehaviorSubject<NotificationModel> didReceiveLocalNotificationSubject =BehaviorSubject<NotificationModel>();

final BehaviorSubject<String> selectNotificationSubject =BehaviorSubject<String>();

class NotificationManage{

   initNotification() async {

    var initializationSettingsAndroid = AndroidInitializationSettings('app_icon');//默认icons

    var initializationSettingsIOS = IOSInitializationSettings(
        onDidReceiveLocalNotification:
            (int id, String title, String body, String payload) async {
          didReceiveLocalNotificationSubject.add(NotificationModel(
              id: id, title: title, body: body, payload: payload));
        });

    var initializationSettings = InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);
    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: (String payload) async {
          if (payload != null) {
            debugPrint('notification payload: ' + payload);
          }
          selectNotificationSubject.add(payload);
        });

  }


  destroyNotification()async{
    flutterLocalNotificationsPlugin.cancelAll();
  }

   destroyNotificationById(int id)async{
     flutterLocalNotificationsPlugin.cancel(id);
   }

  //安卓推送消息 默认
   AndroidNotificationDetails getAndroidPlatformChannelSpecifics(NotificationModel notificationModel){
     if(notificationModel.sound !=null){
       return AndroidNotificationDetails(//安卓配置
           notificationModel.channel.id, //通道 ID随机生成即可
           notificationModel.channel.channelName,//通道名称 实际项目建议采用默认或同一通道管理，方便扩展
           notificationModel.channel.channelDes,//通道描述
           visibility: NotificationVisibility.Public,
           priority:Priority.High,
           sound:RawResourceAndroidNotificationSound(notificationModel.sound),
           styleInformation:notificationModel.styleInformation,
           importance:Importance.High,
           enableLights: true,
           color:  Color.fromARGB(255, 255, 0, 0),
           ledColor: Color.fromARGB(255, 255, 0, 0),
           ledOnMs: 1000,
           ledOffMs:500,
           ticker: 'ticker',
           icon: notificationModel.icon
       );
     }

    return AndroidNotificationDetails(//安卓配置
        notificationModel.channel.id, //通道 ID随机生成即可
        notificationModel.channel.channelName,//通道名称 实际项目建议采用默认或同一通道管理，方便扩展
        notificationModel.channel.channelDes,//通道描述
        visibility: NotificationVisibility.Public,
        priority:Priority.High,
        styleInformation:notificationModel.styleInformation,
        importance:Importance.High,
        ticker: 'ticker',
        icon: notificationModel.icon
    );
  }
  //title body 中配置html的消息通知
   Future<void> createProcessNotification(NotificationModel notificationModel){
      //默认在没有定义前置拦截时，自动填充
      if(notificationModel.androidBeforeSetDetails == null){
        notificationModel.androidBeforeSetDetails=(AndroidNotificationDetails androidNotificationDetails){
          androidNotificationDetails=new AndroidNotificationDetails(
            notificationModel.channel.id, //通道 ID随机生成即可
            notificationModel.channel.channelName,//通道名称 实际项目建议采用默认或同一通道管理，方便扩展
            notificationModel.channel.channelDes,//通道描述
            channelShowBadge: false,
            importance: Importance.Max,
            priority: Priority.High,
            onlyAlertOnce: true,
            showProgress: true,
            indeterminate: true
          );
        };
      }
    //调用默认
    return createDefaultNotification(notificationModel);
  }

    //大文本消息通知
   Future<void> createBigTextNotification(NotificationModel notificationModel){

    var bigTextStyleInformation = BigTextStyleInformation(
        notificationModel.body,
        htmlFormatBigText: true,
        contentTitle: notificationModel.title,
        htmlFormatContentTitle: true,
        summaryText: notificationModel.title,
        htmlFormatSummaryText: true);
        notificationModel.setStyleInformation(bigTextStyleInformation);
    //默认在没有定义前置拦截时，自动填充
    if(notificationModel.androidBeforeSetDetails == null){
      notificationModel.androidBeforeSetDetails=(AndroidNotificationDetails androidNotificationDetails){
        //do some log
      };
    }

    //ios 重新赋值
    if(notificationModel.iosBeforeSetDetails == null){
      notificationModel.iosBeforeSetDetails=(IOSNotificationDetails iosNotificationDetails){
        iosNotificationDetails=null; //在iso中不支持
      };
    }

    //调用默认
    return createDefaultNotification(notificationModel);
  }

  // 消息通知带图片
   Future<void> createPictureNotification(NotificationModel notificationModel) async{
    var picturePath = await _downloadAndSaveFile(notificationModel.resourcePath,new DateTime.now().toString());
    var pictureStyleInformation = BigPictureStyleInformation(
        FilePathAndroidBitmap(picturePath),
        largeIcon:  FilePathAndroidBitmap("app_icon"),
        contentTitle: notificationModel.title,
        htmlFormatContentTitle: true,
        summaryText: notificationModel.body,
        htmlFormatSummaryText: true);
    notificationModel.styleInformation=pictureStyleInformation;
    //默认在没有定义前置拦截时，自动填充
    if(notificationModel.androidBeforeSetDetails == null){
      notificationModel.androidBeforeSetDetails=(AndroidNotificationDetails androidNotificationDetails){

        //do some log
      };
    }

    //ios 重新赋值
    if(notificationModel.iosBeforeSetDetails == null){
      notificationModel.iosBeforeSetDetails=(IOSNotificationDetails iosNotificationDetails){
        iosNotificationDetails=null; //在iso中不支持
      };
    }

    //调用默认
    return createDefaultNotification(notificationModel);
  }

   Future<void> createNotificationWithSound(NotificationModel notificationModel){
     if(notificationModel.sound ==null){
       notificationModel.setSound("slow_spring_board");
     }

    //默认在没有定义前置拦截时，自动填充
    if(notificationModel.androidBeforeSetDetails == null){
      notificationModel.androidBeforeSetDetails=(AndroidNotificationDetails androidNotificationDetails){

        //do some log
      };
    }

    //ios 重新赋值
    if(notificationModel.iosBeforeSetDetails == null){
      notificationModel.iosBeforeSetDetails=(IOSNotificationDetails iosNotificationDetails){
        iosNotificationDetails=new IOSNotificationDetails(
          sound: "slow_spring_board",
          presentSound: true,
          presentAlert:true,
          presentBadge:true,
        );
      };
    }
    //调用默认
    return createDefaultNotification(notificationModel);
  }


   Future<String> _downloadAndSaveFile(String url, String fileName) async {
    var directory = await getApplicationDocumentsDirectory();
    var filePath = '${directory.path}/$fileName';
    var response = await http.get(url);
    var file = File(filePath);
    await file.writeAsBytes(response.bodyBytes);
    return filePath;
  }

  //默认推送消息
   Future<void> createDefaultNotification(NotificationModel notificationModel) async {

    //推送前调用
    if(notificationModel.beforeNotification != null){
      notificationModel.beforeNotification(notificationModel);
    }

    var androidPlatformChannelSpecifics = getAndroidPlatformChannelSpecifics(notificationModel);
    //调用前可对detail重新调整 对应配置可参考官方文档
    if(notificationModel.androidBeforeSetDetails != null){
      notificationModel.androidBeforeSetDetails(androidPlatformChannelSpecifics);
    }

    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    //调用前可对detail重新调整 对应配置可参考官方文档
    if(notificationModel.iosBeforeSetDetails != null){
      notificationModel.iosBeforeSetDetails(iOSPlatformChannelSpecifics);
    }

    var platformChannelSpecifics = NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);

    await flutterLocalNotificationsPlugin.show(
        notificationModel.id, notificationModel.title, notificationModel.body, platformChannelSpecifics,
        payload: notificationModel.payload);

    if(notificationModel.successNotification != null){
      notificationModel.setSuccess(true);
      notificationModel.successNotification(notificationModel);
    }

/*    didReceiveLocalNotificationSubject.stream
        .listen((NotificationModel didModel) async{
          if(notificationModel.successNotification !=null){
            notificationModel.successNotification(didModel);
          }
        });*/

    selectNotificationSubject.stream.listen((String payload) async{
      if(notificationModel.successNotification !=null){
        notificationModel.successNotification(notificationModel);
      }
    });
  }

}